package com.diycode.controller;

import com.diycode.entity.Admins;
import com.diycode.entity.Users;
import com.diycode.enumPackge.UserTypeEnum;
import com.diycode.service.AdminsService;
import com.diycode.service.UsersService;
import com.diycode.utils.MapControl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

@Controller
public class IndexController {
    @Resource
    UsersService userService;
    @Resource
    AdminsService adminsService;

    //跳转系统主页
    @GetMapping("/index")
    public String login() {
        return "index";
    }

    //跳转用户基本信息页面
    @GetMapping("/info")
    public String info() {
        return "info";
    }

    //跳转修改密码页面
    @GetMapping("/pwd")
    public String pwd() {
        return "pwd";
    }

    //修改密码 根据旧密码来修改密码
    @PostMapping("/pwd")
    @ResponseBody
    public Map<String, Object> pwd(String sourcePwd, String newPwd, Integer type, Integer id) {
        //先判断类型
        if (UserTypeEnum.Type_1.getType() == type) {
            Admins user = adminsService.getById(id);
            //比较原密码是否相同 注意：原密码也要加密后再进行比较，因为数据库中存储的是加密后的密码
            if (user.getPassWord().equals(sourcePwd)) {
                Admins entity = new Admins();
                entity.setId(id);
                entity.setPassWord(newPwd);
                if (adminsService.updateById(entity)) {
                    return MapControl.getInstance().success().getMap();
                } else {
                    return MapControl.getInstance().error().getMap();
                }
            } else {
                return MapControl.getInstance().error("原密码错误").getMap();
            }
        } else if (UserTypeEnum.Type_2.getType() == type) {
            Users user = userService.getById(id);
            //比较原密码是否相同 注意：原密码也要加密后再进行比较，因为数据库中存储的是加密后的密码
            if (user.getPassWord().equals(sourcePwd)) {
                Users entity = new Users();
                entity.setUserId(id);
                entity.setPassWord(newPwd);
                if (userService.updateById(entity)) {
                    return MapControl.getInstance().success().getMap();
                } else {
                    return MapControl.getInstance().error().getMap();
                }
            } else {
                return MapControl.getInstance().error("原密码错误").getMap();
            }
        }
        return MapControl.getInstance().error().getMap();
    }

    //跳转系统主页（数据概览）
    @GetMapping("/main")
    public String main(ModelMap modelMap) {

        return "main";
    }

}
